/** 
 * @func 用户行为的采集工作
 * 
*/
import { options } from './options'
import { _support } from '../utils/global'
import { EVENTTYPES, BREADCRUMBTYPES } from '../common/constant';
export class Behaviors {

    task = []
    constructor() {

    }
    // 添加用戶行爲
    push(data) {
        // 判断是否需要格式化 前端传过来的处理函数
        if (typeof options.beforePushBreadcrumb == 'function') {
            data = options.beforePushBreadcrumb(data)
        }
        this._initData(data)
    }
    clear() { this.task = [] }
    shift() { this.task.shift() }
    getTask() { return this.task }
    // 格式化一下，也clru原则
    _initData(data) {
        data.time == data.time || Date.now()
        // 超过最大占内存就移除最险最远的
        if (this.task.length >= options.maxBreadCrumbs) {
            this.shift()
        }
        this.task.push(data)
        this.task.sort((a, b) => a.time - b.time)
    }
    getCategory(type) {
        switch (type) {
            // 接口请求
            case EVENTTYPES.XHR:
            case EVENTTYPES.FETCH:
                return BREADCRUMBTYPES.HTTP;

            // 用户点击
            case EVENTTYPES.CLICK:
                return BREADCRUMBTYPES.CLICK;

            // 路由变化
            case EVENTTYPES.HISTORY:
            case EVENTTYPES.HASHCHANGE:
                return BREADCRUMBTYPES.ROUTE;

            // 加载资源
            case EVENTTYPES.RESOURCE:
                return BREADCRUMBTYPES.RESOURCE;

            // Js代码报错
            case EVENTTYPES.UNHANDLEDREJECTION:
            case EVENTTYPES.ERROR:
                return BREADCRUMBTYPES.CODEERROR;

            // 用户自定义
            default:
                return BREADCRUMBTYPES.CUSTOM;
        }
    }

}
const behaviors = _support.behaviors || (_support.behaviors = new Behaviors())

export { behaviors }